package helper

import (
	"encoding/json"
	"io/ioutil"
	"log"
	"os"
)

type GitCmd struct {
	Cmd string `json:"cmd"`
}

type App struct {
	Port string             `json:"port"`
	Cmds map[string]*GitCmd `json:"cmds"`
}

type Request struct {
	Flag string `form:"flag" binding:"required"  json:"flag"`
}

var AppConfig *App

//var Cmds = make([]GitCmd, 0)

func GetAppConfig(path string) *App {
	app := &App{"", make(map[string]*GitCmd, 0)}
	jsonStr := GetFileContent(path)

	if jsonStr == "" {
		return nil
	}

	err := json.Unmarshal([]byte(jsonStr), app)

	if err != nil {
		log.Println("json ummarshal err :", err)
		return nil
	}
	return app
}

func GetFileContent(path string) string {
	file, err := os.Open(path)
	if err != nil {
		log.Println("open the config file error :", err)
		return ""
	}

	b, err := ioutil.ReadAll(file)

	if err != nil {
		log.Println("read the config file error :", err)
		return ""
	}
	return string(b)
}
